using System;
using System.Collections;
using System.IO;
using System.IO.IsolatedStorage;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using flickr.api;
using FlickrShots.Framework.Windows;

namespace FlickrShots.Framework
{
	[Serializable]
	public class Preferences : Hashtable, IDisposable
	{
		static private Assembly _entryAssembly = Assembly.GetAssembly(typeof(Preferences));
		static private string _preferencesFileName = _entryAssembly.GetName().Name + ".dat";
	    public static readonly Preferences Instance = new Preferences();
        private bool IsLoaded = false;

	    private Preferences()
		{
			Load();
		}

	    protected Preferences(SerializationInfo info, StreamingContext context)
			: base(info,context){}

		public void LoadDefaultPreferences()
        {
			FlickrUserName = null;
			Token = null;
		    PhotoFolder = "C:\\temp";

            Flickr.ApiKey = Preferences.ApiKey;
            Flickr.SharedSecret = Preferences.SharedSecret;

			Save();
		}

		public string FlickrUserName
		{
			get { return GetPreference("FlickrUserName"); }
			set { SetPreference("FlickrUserName", value); }
		}

		public string Tags
        {
            get { return GetPreference("Tags"); }
            set { SetPreference("Tags", value); }
        }

		public string Token
		{
			get { return GetPreference("Token"); }
			set { SetPreference("Token", value); Save(); }
		}

	    public string PhotoFolder
	    {
	        get { return GetPreference("PhotoFolder"); }
            set { SetPreference("PhotoFolder", value); }
	    }
	    
	    public WPSTYLE WallpaperPosition
	    {
            get { return (WPSTYLE)Enum.Parse(typeof(WPSTYLE), GetPreference("WallpaperPosition")); }
            set { SetPreference("WallpaperPosition", value.ToString()); }
        }
	    
	    public TimeSpan AutoRefreshRate
	    {
            get {
                string refreshRate = GetPreference("AutoRefreshRate");
                if (refreshRate == null)
                    return new TimeSpan(0,1,0);
                return TimeSpan.Parse(refreshRate); 
            }
            set { SetPreference("AutoRefreshRate", value.ToString()); }
        }

	    private void SetPreference(string key, object value)
	    {
	        this[key] = value;
	    }

	    private string GetPreference(string key)
	    {
	        return this[key] != null ? this[key].ToString() : null;
	    }

	    public static string ApiKey
		{
			get { return "5a3f78d9a0f34169777dbb3ff266ba06"; }
		}

	    public static string SharedSecret
		{
			get { return "9a588396d92994b9"; }
		}

	    public void Dispose()
		{
			Save();
		}

	    public void Load()
		{
            if (!IsLoaded)
            {
                IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User
                    | IsolatedStorageScope.Assembly, null, null);
                if (isoStore.GetFileNames(_preferencesFileName).Length == 0)
                {
                    LoadDefaultPreferences();
                    Save();
                    return;
                }

                // Read the stream from Isolated Storage.
                Stream stream = new IsolatedStorageFileStream(_preferencesFileName,
                    FileMode.OpenOrCreate, isoStore);
                if (stream != null)
                {
                    try
                    {
                        // DeSerialize the Hashtable from stream.
                        IFormatter formatter = new BinaryFormatter();
                        Hashtable appData = (Hashtable)formatter.Deserialize(stream);

                        // Enumerate through the collection and load our base Hashtable.
                        IDictionaryEnumerator enumerator = appData.GetEnumerator();
                        while (enumerator.MoveNext())
                        {
                            this[enumerator.Key] = enumerator.Value;
                        }
                    }
                    finally
                    {
                        // We are done with it.
                        stream.Close();
                    }
                }
                IsLoaded = true;
            }
		}

	    public void Save()
		{
			// Open the stream from the IsolatedStorage.
			IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore( IsolatedStorageScope.User 
				| IsolatedStorageScope.Assembly, null, null );
			Stream stream = new IsolatedStorageFileStream( _preferencesFileName, 
			                                               FileMode.Create, isoStore );
        
			if ( stream != null )
			{
				try
				{
					// Serialize the Hashtable into the IsolatedStorage.
					IFormatter formatter = new BinaryFormatter();
					formatter.Serialize( stream, (Hashtable)this );
				}
				finally
				{
					stream.Close();
				}
			}
		}

	    public void Reload()
		{
			Load();
		}

	}
}
